import { login, changePwd, logout, getInfo, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken, getUsername, setUsername, removeUsername } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
    token: getToken(),
    username: getUsername(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    id: '',
    readedid: '',
    stateobj: {},
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = decodeURIComponent(encodeURIComponent(token))
    },
    SET_INTRODUCTION: (state, introduction) => {
        state.introduction = introduction
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_USERNAME: (state, username) => {
        state.username = username
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    },
    SET_ID: (state, id) => {
        state.id = id
    },
    SET_PROFILE: (state, info) => {
        state.profile = info
    },
    SET_READID: (state, readedid) => {
        state.readedid = readedid
    },
    SET_STATEOBJ: (state, stateobj) => {
        state.stateobj = stateobj
    },
}

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { username, password } = userInfo
        return new Promise((resolve, reject) => {
            login({ username: username, password: password }).then(response => {
                const { data } = response;
                commit('SET_TOKEN', data.token)
                commit('SET_USERNAME', data.username)
                commit('SET_ID', data.userId)
                setToken(data.token)
                setUsername(data.username)
                resolve(response)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo(state.username).then(response => {
                const { data } = response
                if (!data) {
                    reject('验证失败，请重新登录！')
                }
                const { userId, roles, name, avatar, introduction } = data
                // roles must be a non-empty array
                if (!roles || roles.length <= 0) {
                    reject('获取用户/角色信息: 角色必须是非空数组！')
                }
                console.log('用户信息', data);
                commit('SET_ROLES', roles)
                commit('SET_NAME', name)
                commit('SET_AVATAR', avatar)
                commit('SET_INTRODUCTION', introduction)
                commit('SET_ID', userId)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    getUserInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getUserInfo(state.id).then(response => {
                const { data } = response
                commit('SET_PROFILE', data);
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    /* 修改密碼*/
    changePwd({ state }, obj) {
        return new Promise((resolve, reject) => {
            changePwd({ id: state.id, ...obj }).then((response) => {
                if (response.data.success) {
                    resolve(response)
                }
            }).catch(error => {
                reject(error)
            })
        })
    },
    // 退出
    logout({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then(() => {
                commit('SET_TOKEN', '')
                commit('SET_ROLES', [])
                removeToken()
                removeUsername()
                resetRouter()

                // reset visited views and cached views
                // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
                dispatch('tagsView/delAllViews', null, { root: true })

                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken()
            removeUsername()
            resolve()
        })
    },

    // dynamically modify permissions
    changeRoles({ commit, dispatch }, role) {
        return new Promise(async resolve => {
            /* const token = role + '-token'*/
            const token = role
            commit('SET_TOKEN', token)
            setToken(token)

            const { roles } = await dispatch('getInfo')

            resetRouter()

            // generate accessible routes map based on roles
            const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

            // dynamically add accessible routes
            router.addRoutes(accessRoutes)

            // reset visited views and cached views
            dispatch('tagsView/delAllViews', null, { root: true })

            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
